package com.example.node.base;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import com.example.node.listener.OnRequestPermissionListener;
import java.util.ArrayList;
import java.util.List;

public class BasePermissionActivity extends Activity {

    private static final String TAG="BasePermissionActivity";
    /**
     * 1.请求权限
     * checkPermissions:权限数组    回调code  知道结果(回调)
     * 2.处理权限
     */

    private int permissionRequestCode;
    private List<String> mListPermissions=new ArrayList<>();
    private OnRequestPermissionListener listener;

    //请求权限
    protected void checkPermissions(String[] permissions, int requestCode, OnRequestPermissionListener listener){
        //判断不能为空
        if(permissions!=null&&permissions.length!=0){
            permissionRequestCode=requestCode;
            this.listener=listener;
            //先去遍历你的权限  相机 电话 SD卡 List装载未申请的权限
            for (int i=0;i<permissions.length;i++){
                //判断未申请,就装载起来
                if(!checkSelfPermissions(permissions[i])){
                    mListPermissions.add(permissions[i]);
                }
            }
            //遍历完之后申请
            applyPermissions();
        }else{
            listener.onNullPermission();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==permissionRequestCode){
            if(grantResults.length>0){
                listener.onSuccessful(grantResults);
            }else {
                listener.onFailure();
            }
        }
    }

    //检查权限
    private boolean checkSelfPermissions(String permissions){
        int permissionCheck= ContextCompat.checkSelfPermission(this, permissions);
        if(permissionCheck == PackageManager.PERMISSION_GRANTED){
            return true;
        }
        return false;
    }

    //申请权限
    private void applyPermissions(){
        //判断权限集合是否为空
        if(!mListPermissions.isEmpty()){
            //申请权限
            int size=mListPermissions.size();
            ActivityCompat.requestPermissions(this,mListPermissions.toArray(new String[size]),permissionRequestCode);
            mListPermissions.clear();
        }else {
            listener.onOkPermiss();
        }
    }
}
